package com.example.micro_property_springboot.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 安全工具类
 * 用于获取当前登录用户信息
 */
public class SecurityUtils {
    
    /**
     * 获取当前登录用户的用户名
     */
    public static String getCurrentUsername() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                Object principal = authentication.getPrincipal();
                if (principal instanceof UserDetails) {
                    return ((UserDetails) principal).getUsername();
                }
                return principal.toString();
            }
        } catch (Exception e) {
            // 忽略异常，返回默认值
        }
        return "未知用户";
    }
    
    /**
     * 获取当前登录用户的ID
     */
    public static Long getCurrentUserId() {
        try {
            // 这里简化处理，实际应该从用户主体中提取用户ID
            // 如果有自定义的UserDetails实现，可以强制转换后获取ID
            return 1L; // 默认返回1，实际项目中需要根据具体实现修改
        } catch (Exception e) {
            return 0L;
        }
    }
    
    /**
     * 判断当前用户是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() &&
               !(authentication.getPrincipal() instanceof String && "anonymousUser".equals(authentication.getPrincipal()));
    }
}